const { log } = require("console")

let db = null

const ContentType = 'application/x-www-form-urlencoded; charset=UTF-8'

//时间转换
function dateParse(str) {
    if (str === null || str === '')
        return 157737600000
    let arr = str.split('')
    if (arr.length === 4)
        return Date.parse(str)
    else if (arr.length === 6) {
        arr.splice(4, 0, '-')
        return Date.parse(arr.join(''))
    } else if (arr.length === 8) {
        arr.splice(4, 0, '-')
        arr.splice(7, 0, '-')
        return Date.parse(arr.join(''))
    } else return 157737600000
}


/**
 * 阿里云API接口
 * @param isbn ISBN号
 * @returns {Promise<void>}
 */
async function queryAliCloud(isbn) {
    const book = db.collection("book_cache")
    const url = 'https://jmisbn.market.alicloudapi.com/isbn/query'
    const Authorization = 'APPCODE 48b7680d8be64610a5d2ec04d8825fff'
    return await uniCloud.httpclient.request(url, {
        method: 'POST',
        dataType: 'json',
        headers: {
            Authorization,
            'Content-Type': ContentType
        },
        data: {
            'isbn': isbn
        }
    }).then(async res => {
        //存储数据
        if (res.data.data.details.length < 0) {
            return null
        }
        let bookInfo = res.data.data.details[0]
        let pubDate = dateParse(bookInfo.pubDate)
        let bookItem = {
            name: bookInfo.title,
            isbn: isbn,
            cover: bookInfo.img,
            author: bookInfo.author,
            pubHouse: bookInfo.publisher,
            pubDate: pubDate,
            pages: bookInfo.page,
            price: bookInfo.price,
            language: bookInfo.language,
            desc: bookInfo.gist,
            ps: bookInfo.cipTxt
        }
        await book.add(bookItem)
        return bookItem
    }).catch(error => error.message)
}

/**
 * 极客API
 * @param isbn isbn号
 * @returns {Promise<*>}
 */
async function queryJike(isbn)
{
    const book = db.collection("book_cache")
    const url = 'https://api.jike.xyz/situ/book/isbn/' + isbn
    const apiKey = '14652.d8b18c7d78e62a1355bbc4f0cd1310ff.f657cc7a57dff275fa6c60f76916a849'
    return await uniCloud.httpclient.request(url, {
        method: 'get',
        dataType: 'json',
        headers: {
            'Content-Type': ContentType
        },
        data: {
            'apikey': apiKey
        }
    }).then(async res => {
        //存储数据
        if (res.data === {}) {
            return null
        }
        let bookInfo = res.data.data
		let pubDate = ''
		if(bookInfo.published){
			pubDate = dateParse(bookInfo.published.replace(/-/g, ''))
		}
        let bookItem = {
            name: bookInfo.name,
            isbn: isbn,
            cover: bookInfo.photoUrl,
            author: bookInfo.author,
            pubHouse: bookInfo.publishing,
            pubDate: pubDate,
            pages: bookInfo.pages,
            price: bookInfo.price.replace('元',''),
            language: bookInfo.language,
            desc: bookInfo.description,
            ps: `豆瓣评分：${bookInfo.doubanScore}`
        }
        await book.add(bookItem)
        return bookItem
    }).catch(error => error.message)
}

module.exports = {
    _before() {
        //获取数据库引用
        db = uniCloud.databaseForJQL({
            clientInfo: this.getClientInfo()
        })
    },
    
    /**
     * 调取第三方接口获取图书详细信息
     * @param isbn ISBN号码
     * @returns {Promise<*>}
     */
    async getBookInfo(isbn) {
        //先查询数据库中是否有此书信息
        const book = db.collection("book_cache")
        const res = await book
            .where({
                isbn: isbn
            })
            .get()
        let data = res.data
        //有则直接返回
        if (data.length > 0) {
            return data[0]
        } else {
            //没有就查询一下
            return queryAliCloud(isbn)
            // return queryJike(isbn)
        }
    },
	
	async updateInfo(){
		// 先查询没有封面的图书
		const book = (await db.collection("book").where({
			cover:''
		}).get()).data
		for (const item of book) {
            let res  = (await db.collection('book_cache')
                .where({
                    isbn: item.isbn
                })
                .get()).data[0]
            await db.collection("book").doc(item._id).update({
                name: res.name,
                isbn: res.isbn,
                cover: res.cover,
                author: res.author,
                pubHouse: res.pubHouse,
                pubDate: res.pubDate,
                desc: res.desc
            })
        }
    }
    
    
}
